package com.manager
{
	import com.adobe.catalog.qs.controls.SuperImage;
	import com.adobe.catalog.qs.fzip.FZip;
	import com.adobe.catalog.qs.fzip.FZipFile;
	import com.event.DeleteImageEvent;
	import com.view.ImageListView;
	import com.view.LoadingView;
	import com.vo.PictureVO;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.DisplayObject;
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.media.Sound;
	import flash.media.SoundChannel;
	import flash.media.SoundTransform;
	import flash.net.FileFilter;
	import flash.net.FileReference;
	import flash.net.FileReferenceList;
	import flash.utils.ByteArray;
	
	import flashx.textLayout.factory.TruncationOptions;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.controls.DateField;
	import mx.controls.SWFLoader;
	import mx.core.ByteArrayAsset;
	import mx.core.FlexGlobals;
	import mx.core.IFlexDisplayObject;
	import mx.formatters.DateFormatter;
	import mx.graphics.codec.JPEGEncoder;
	import mx.managers.PopUpManager;
	import mx.utils.UIDUtil;
	
	import spark.components.Image;
	
	[Event(name="bookPageRefresh",type="flash.events.Event")]
	
	[Event(name="soundVolumnChange",type="flash.events.Event")]
	[Event(name="widthChange",type="flash.events.Event")]
	[Event(name="heightChange",type="flash.events.Event")]
	public class BookManager extends EventDispatcher
	{
		public static const BOOK_PAGE_REFRESH:String = "bookPageRefresh";
		
		private static var _instace:BookManager;
		
		[Bindable]
		public var bookSuperImageList:ArrayCollection = new ArrayCollection();
		
		[Bindable]
		public var bookCartList:ArrayCollection = new ArrayCollection();
		
		[Embed(source="com/resource/BookCreate.swf", mimeType="application/octet-stream")]
		private var bookTemplate:Class;
		[Embed(source="com/resource/BookCreate.html", mimeType="application/octet-stream")]
		private var bookHtml:Class;
		
		[Bindable]
		public var isOpen:Boolean = false;
		
		private var imagesFilter:FileFilter = new FileFilter("Images", "*.jpg;*.gif;*.png");
		
		private var soundFilter:FileFilter = new FileFilter("Sound","*.mp3");
		
		private var fileReferenceList:FileReferenceList;
		
		private var imageListPop:ImageListView;
		
		[Bindable]
		public var bookWidth:Number = 80;
		
		[Bindable]
		public var bookHeight:Number = 80;
		
		[Bindable]
		public var borderEnable:Boolean = true;
		
		[Bindable]
		public var borderThickness:int = 5;
		
		[Bindable]
		public var borderColor:uint = 0xffffff;
		
		[Bindable]
		public var shadowEnable:Boolean = true;
		
		[Bindable]
		public var shadowThickness:int = 3;
		
		[Bindable]
		public var shadowDistance:int = 5;
		
		[Bindable]
		public var shadowAngle:int = 45;
		
		[Bindable]
		public var shadowColor:uint = 0x000000;
		
		[Bindable]
		public var musicOn:Boolean = true;
		
		[Bindable]
		public var music:SoundChannel = new SoundChannel();
		
		[Bindable]
		public var backMusicName:String;
		
		[Bindable]
		public var backMusic:ByteArray;
		
		[Bindable]
		public var soundTransformer:SoundTransform = new SoundTransform();
		
		public function BookManager(target:IEventDispatcher=null)
		{
			super(target);
			dateFormat = new DateFormatter();
			dateFormat.formatString = "YYYY_MM_DD_HH_	MM_SS";
			addEventListener(DeleteImageEvent.DELETE_IMAGE,onDeleteImageHandler );
		}
		
		public static function getInstance():BookManager
		{
			if( !_instace )
			{
				_instace = new BookManager();
				
			}
			return _instace;
		}
		
		public function refreshBookSource():void
		{
			bookSuperImageList.removeAll();
			for(var i:int=0;i<bookCartList.length;i++)
			{
				var bookPageVo:PictureVO = bookCartList[i] as PictureVO;
				var bookPage:Image = new Image();
				bookPage.fillMode = "scale";
				bookPage.scaleMode = "stretch";
				bookPage.source = bookPageVo.bitmap;
				bookSuperImageList.addItem( bookPage );
			}
			dispatchEvent( new Event(BOOK_PAGE_REFRESH));
		}
		
		public function addBookPages(bookPages:PictureVO):void
		{
			bookPages.index = bookCartList.length+1;
			bookCartList.addItem( bookPages );
//			for each( var item:PictureVO in bookPages )
//			{
//				var bookPage:Image = new Image();
//				bookPage.fillMode = "scale";
//				bookPage.scaleMode = "stretch";
//				bookPage.source = bookPages.bitmap;
//				bookSuperImageList.addItem( bookPage );
//			}
			dispatchEvent( new Event(BOOK_PAGE_REFRESH));
		}
		
		private function loadSwfBytes():void
		{
//			var loader:Loader = new Loader();
//			loader.contentLoaderInfo.addEventListener(Event.COMPLETE,function onComplete( event:Event ):void
//			{
//				loader.
//			});
//			loader.loadBytes(new bookTemplate() as ByteArray);
			
		}
		
		private var dateFormat:DateFormatter;
		public function bulidZipFile():void
		{
			//弹出loadingView
//			pop = PopUpManager.createPopUp(FlexGlobals.topLevelApplication as DisplayObject,LoadingView,true);
//			LoadingView(pop).setLabel("正在初始化配置文件..");
//			PopUpManager.centerPopUp( pop );
			//首先生成一个zip对象
			
			try
			{
				var zip:FZip = new FZip();
				
				var configXml:XML = <Config bookWidth={bookWidth} bookHeight={bookHeight} borderThickness={borderThickness} borderColor={borderColor.toString(16)}
				shadowThickness={shadowThickness} shadowDistance={shadowDistance} shadowRotation={shadowAngle}/>;
				
				//将图片文件打包进zip
				var imageNumber:int = bookSuperImageList.length;
				for( var i:int=0;i<imageNumber;i++)
				{
					var item:Image = bookSuperImageList.getItemAt(i) as Image;
//					LoadingView(pop).run(i+1,imageNumber);
//					LoadingView(pop).setLabel("已生成"+(currentIndex+1)+"张/共"+imageNumber+"张..");
					var bytes:ByteArray = item.source as ByteArray;
					var name:String = UIDUtil.createUID()+".jpg";
					zip.addFile("resource/"+name,bytes);
					
					var itemXml:XML = <Picture url={"resource/"+name}/>;
					configXml.appendChild(itemXml);
				}
				
				//将声音打包进zip
				if( backMusic )
				{
//					LoadingView(pop).setLabel("正在生成背景音乐文件..");
					zip.addFile("resource/BGM.mp3",backMusic );
				}
				
				//生成配置文件
				zip.addFileFromString("Config.xml",configXml.toString());
				//生成html文件
				var byteHtml:ByteArray = new bookHtml() as ByteArray;
				zip.addFile("BookCreate.html",byteHtml);
				
				//生成swf
				var byteArray:ByteArray = new bookTemplate() as ByteArray;
				zip.addFile("BookCreate.swf",byteArray);
				
				var outPutBytes:ByteArray = new ByteArray();
				zip.serialize(outPutBytes);
			}catch(e:Error)
			{
				Alert.show("生成文件失败，请联系管理员!");
//				if( pop )
//				{
//					PopUpManager.removePopUp( pop );
//					pop = null;
//				}
				return;
			}
			var file:FileReference = new FileReference();
			file.save(outPutBytes,"生成文件.zip");
			//关闭loadingView
//			if( pop )
//			{
//				PopUpManager.removePopUp( pop );
//				pop = null;
//			}
		}
		
		//上传图片
		public function uploadImage():void
		{
			fileReferenceList = new FileReferenceList();
			fileReferenceList.addEventListener(Event.SELECT,onSelectedHandler );
			fileReferenceList.browse([imagesFilter]);
		}
		
		private var fileNumber:int=0;
		private var pop:IFlexDisplayObject;
		private var currentIndex:int = 0;
		private function onSelectedHandler( event:Event ):void
		{
			if( !isOpen )
				isOpen = true;
			//弹出loading窗口
			pop = PopUpManager.createPopUp(FlexGlobals.topLevelApplication as DisplayObject,LoadingView,true);
			LoadingView(pop).setLabel("正在上传图片");
			PopUpManager.centerPopUp( pop );
			
			var fileList:Array = (event.currentTarget as FileReferenceList).fileList;
			fileNumber = fileList.length;
			var file:FileReference;
			for( var i:int=0;i<fileNumber;i++)
			{
				file = fileList[i] as FileReference;
				file.addEventListener(Event.COMPLETE,onCompleteHandler );
				file.addEventListener(ProgressEvent.PROGRESS,onProgressHandler );
				file.addEventListener(SecurityErrorEvent.SECURITY_ERROR,onErrorHandler );
				file.addEventListener(IOErrorEvent.IO_ERROR,onErrorHandler );
				file.load();
			}
		}
		
		private function onProgressHandler( event:ProgressEvent ):void
		{
			var fileReference:FileReference = event.currentTarget as FileReference;
		}
		
		private function onCompleteHandler(event:Event):void
		{
			currentIndex++;
			if( (currentIndex <= fileNumber) && pop)
			{
				LoadingView(pop).run(currentIndex,fileNumber);
				LoadingView(pop).setLabel("已上传"+currentIndex+"张/共"+fileNumber+"张");
				if( currentIndex == fileNumber )
				{
					currentIndex = 0;
					PopUpManager.removePopUp( pop );
					pop = null;
				}
			}
			var fileReference:FileReference = event.currentTarget as FileReference;
			var picture:PictureVO = new PictureVO();
			picture.name = fileReference.name;
			picture.bitmap = fileReference.data;
			
			addBookPages(picture);
			refreshBookSource();
		}
		
		private function onErrorHandler(event:Event):void
		{
			Alert.show("抱歉!加载失败");
		}
		
		
		//用户点击删除图片的时候触发
		private function onDeleteImageHandler(event:DeleteImageEvent):void
		{
			var picture:PictureVO = event.imageData;
			for( var i:int=0;i<bookCartList.length;i++)
			{
				if( bookCartList[i] == picture )
				{
					bookCartList.removeItemAt(i);
					break;
				}
			}
			refreshBookSource();
		}
		
		//清空所有照片
		public function deleteAllImage():void
		{
			bookCartList.removeAll();
			refreshBookSource();
		}
		
		//上传背景音乐
		public function uploadBackgroundMusic():void
		{
			var file:FileReference = new FileReference();
			file.addEventListener(Event.SELECT,onBGMSelctedHandler);
			file.browse([soundFilter]);
		}
		
		private var musicFile:FileReference;
		private function onBGMSelctedHandler( event:Event ):void
		{
			deleteBackgroundMusic();
			musicFile = event.currentTarget as FileReference;
			//弹出loading窗口
			pop = PopUpManager.createPopUp(FlexGlobals.topLevelApplication as DisplayObject,LoadingView,true);
			LoadingView(pop).setLabel("正在上传背景音乐");
			PopUpManager.centerPopUp( pop );
			
			musicFile.addEventListener(Event.COMPLETE,onBGMCompleteHandler );
			musicFile.addEventListener(ProgressEvent.PROGRESS,onBGMProgressHandler );
			musicFile.addEventListener(SecurityErrorEvent.SECURITY_ERROR,onErrorHandler );
			musicFile.addEventListener(IOErrorEvent.IO_ERROR,onErrorHandler );
			musicFile.load();
		}
		
		private function onBGMCompleteHandler( event:Event ):void
		{
			var musicFile:FileReference = event.currentTarget as FileReference;
			//关闭loadingView
			if( pop )
			{
				PopUpManager.removePopUp( pop );
				pop = null;
			}
			backMusicName = musicFile.name;
			backMusic = musicFile.data;
			var sound:Sound = new Sound();
			sound.loadCompressedDataFromByteArray(backMusic,backMusic.length);
			music = sound.play(0,100);
			soundTransformer.volume = 0.5;
			music.soundTransform = soundTransformer;
		}
		
		private function onBGMProgressHandler( event:ProgressEvent ):void
		{
			if( pop )
			{
				LoadingView(pop).run(event.bytesLoaded,event.bytesTotal);
			}
		}
		public function deleteBackgroundMusic():void
		{
			backMusicName = "";
			backMusic = null;
			if( music )
				music.stop();
		}
		
		public function setSoundToggle(isToggle:Boolean):void
		{
			if( isToggle )
			{
				changeVolume(0)
			}
			else
			{
				changeVolume(0.5)
			}
		}
		
		public function changeVolume(volume:Number):void
		{
			soundTransformer.volume = volume;
			music.soundTransform = soundTransformer;
			dispatchEvent(new Event("soundVolumnChange"));
		}
		
		public function changeWidth():void
		{
			dispatchEvent( new Event("widthChange"));
		}
		
		public function changeHeight():void
		{
			dispatchEvent( new Event("heightChange"));
		}
	}
}